﻿Imports System.Text.RegularExpressions
Imports System.ComponentModel

Public Class NewProfileForm
    Implements INotifyPropertyChanged



    Public Property Profile As ClientProfile
    Public Property Password As String
    Public Property Keylength As Integer = 1024

    Private ErrorBrush As Brush
    Private Blacklist As IEnumerable(Of String)
    Public ReadOnly Property IsDataOk As Boolean
        Get
            Dim ok As Boolean = True
            'ceck fields are not empty
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbName.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbSurname.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbOrganization.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbOrganizationUnit.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbEmail.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbUsername.Text)
            ok = ok AndAlso Not String.IsNullOrWhiteSpace(tbPassword.Password)

            'checks email is ok
            ok = ok AndAlso Regex.IsMatch(tbEmail.Text, "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")

            'check username is ok
            ok = ok AndAlso Regex.IsMatch(tbUsername.Text, "^[a-zA-Z0-9]+$") AndAlso Not Blacklist.Contains(tbUsername.Text)

            'check password is ok
            ok = ok AndAlso tbPassword.Password = tbPasswordAgain.Password

            Return ok
        End Get
    End Property

    Public Sub New(existingUsers As IEnumerable(Of String))
        Blacklist = existingUsers
        Profile = New ClientProfile

#If DEBUG Then
        'Fill fields for faster testing
        Profile.Name = "Elia"
        Profile.Surname = "Dal Santo"
        Profile.Organization = "Unipd"
        Profile.OragnizationUnit = "Studenti.Math"
        Profile.UserName = "elia"
        Profile.eMailAddress = "edalsant@math.unipd.it"
#End If


        Dim b As New SolidColorBrush
        b.Color = New Color With {
            .A = 100,
            .R = 255,
            .G = 0,
        .B = 0
        }
        ErrorBrush = b
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ComboCountry.ItemsSource = CountryCodeUtilities.getCountryCodes()

#If DEBUG Then
        ComboCountry.SelectedIndex = 0
        tbPassword.Password = "elia"
        tbPasswordAgain.Password = "elia"
#End If
    End Sub

    Private Sub ComboCountry_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        If e.AddedItems.Count > 0 Then
            Profile.Country = DirectCast(e.AddedItems(0), CountryCode).Code
        End If
    End Sub


    Private Sub TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        Dim tb = DirectCast(sender, TextBox)
        Select Case tb.Name
            Case "tbName", "tbSurname", "tbOrganization", "tbOrganizationUnit"
                If String.IsNullOrWhiteSpace(tb.Text) Then
                    tb.Background = ErrorBrush
                Else
                    tb.Background = Brushes.White
                End If
            Case "tbEmail"
                If String.IsNullOrWhiteSpace(tb.Text) OrElse
                   Regex.IsMatch(tb.Text, "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$") = False Then
                    tb.Background = ErrorBrush
                Else
                    tb.Background = Brushes.White
                End If
            Case "tbUsername"
                If String.IsNullOrWhiteSpace(tb.Text) OrElse
                   Regex.IsMatch(tb.Text, "^[a-zA-Z0-9]+$") = False OrElse Blacklist.Contains(tb.Text) Then
                    tb.Background = ErrorBrush

                    If Blacklist.Contains(tb.Text) Then
                        tb.ToolTip = "The username you chose is already in use. Please choose a different one"
                    Else
                        tb.ToolTip = "The username must contain only letters and/or numbers"
                    End If

                Else
                    tb.Background = Brushes.White
                    tb.ToolTip = "Enter your desired username"
                End If
        End Select

        UpdateStatus()
        OnPropertyChanged("IsDataOk")
    End Sub


    Private Sub buttonOkCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim w = TryCast(Me.Parent, Window)
        If w IsNot Nothing Then
            w.DialogResult = sender Is buttonOk
            w.Close()
        End If
    End Sub

    Private Sub PasswordChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)


        If tbPassword.Password = tbPasswordAgain.Password Then
            tbPasswordAgain.Background = Brushes.White
            Password = tbPassword.Password
        Else
            tbPasswordAgain.Background = ErrorBrush
        End If

        UpdateStatus()
        OnPropertyChanged("IsDataOk")
    End Sub

    Private Sub ComboKeylength_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
        Keylength = CInt(cbKeylength.SelectedValue)
    End Sub

    Private Sub UpdateStatus()
        If Not Me.IsLoaded Then
            Return
        End If

        textStatus.Text = "Username and password are valid"
        textStatus.Foreground = Brushes.Green

        If Blacklist.Contains(tbUsername.Text) Then
            textStatus.Text = "Username is taken, please chose a different one"
            textStatus.Foreground = Brushes.Red
            Return
        End If

        If Regex.IsMatch(tbUsername.Text, "^[a-zA-Z0-9]+$") = False Then
            textStatus.Text = "Username contains invalid characters, please use letters and numbers only."
            textStatus.Foreground = Brushes.Red
            Return
        End If

        If tbPassword.Password <> tbPasswordAgain.Password Then
            textStatus.Text = "Passwords don't match!"
            textStatus.Foreground = Brushes.Red
            Return
        End If

        If String.IsNullOrWhiteSpace(tbPassword.Password) Then
            textStatus.Text = "Password missing."
            textStatus.Foreground = Brushes.Red
            Return
        End If


    End Sub

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
    Private Overloads Sub OnPropertyChanged(name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub
End Class
